package agent;

import instanceXMLParser.Instance;

import java.awt.Point;
import java.util.ArrayList;
import java.util.Map;

import vca.Enviroment;
import vca.Solution;
import aima.core.agent.Action;
import aima.core.agent.AgentProgram;
import aima.core.agent.Percept;
import aima.core.agent.impl.AbstractAgent;
import aima.core.agent.impl.DynamicAction;
import aima.core.agent.impl.NoOpAction;
import core.LocalVacuumEnvironmentPercept;
import core.VacuumEnvironment;

public class GAGreedy extends AbstractVacuumSolver implements Runnable{
	private Enviroment ev;
	private ArrayList<String> actions= new ArrayList<>();
	private LocalVacuumEnvironmentPercept vep;
	private final String id= "GAGREEDY";
	private static int MAX_INDIVIDUAL_SIZE = 40;

	
	
	
	public String getId() {
		return id;
	}

	public GAGreedy(LocalVacuumEnvironmentPercept vep) {
		this.vep = vep;
	}
	
	public ArrayList<Action> getSolution(){
		
		ArrayList<Action> sol = new ArrayList<>();
		
		for (String s : actions) {
			sol.add(new DynamicAction(s));
		}
		
		sol.add(NoOpAction.NO_OP);
		
		return sol;
	}
	
	public void solve(LocalVacuumEnvironmentPercept vep){
		Enviroment.SUCK_COST = vep.getActionEnergyCosts().get(new DynamicAction("suck")).intValue();
		Map<Point, VacuumEnvironment.LocationState> map = vep
				.getState();
		int matrix[][] = new int[vep.getN()][vep.getN()];
		ArrayList<Point> dt = new ArrayList<>();
		for (Point p : map.keySet()) {
			if (map.get(p).ordinal() == Enviroment.DIRTY) {
				dt.add(p);
			}
			matrix[p.x][p.y] = map.get(p).ordinal();
		}
		Point base = vep.getBaseLocation();
		Point agentPos = vep.getAgentLocation();
		matrix[base.x][base.y] = Enviroment.BASE;
		
		int iterationNumber = 1 + (MAX_INDIVIDUAL_SIZE)-dt.size();
		
		ev = new Enviroment(matrix, dt, base,agentPos, 100, iterationNumber, vep
				.getInitialEnergy().intValue());

		dt = ev.getDt();
		
		if(!ev.isBaseReachable()){
			//System.out.println("Base is not reachable");
			return;
		}

		if (dt.size() > MAX_INDIVIDUAL_SIZE || dt.size()==0) {
			Solution s1 = ev.greedyAlgorithm();
			actions = s1.actions;
			System.out.println(s1.performanceMesure);
		} else {
			Solution s1 = ev.greedyAlgorithm();
			Solution s2 = ev.geneticAlgorithm();

			System.out.println(s1.performanceMesure);
			System.out.println(s2.performanceMesure);
			
			if (s1.performanceMesure >= s2.performanceMesure)
				actions = s1.actions;
			else
				actions = s2.actions;
		}

	}

	@Override
	public void solve(String path) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void solveFromInstance(Instance i) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void run() {
		this.solve(vep);
	}
	
}
